﻿//***********************************************************************
// Assembly         : IGolovkine.AoA.Tests
// Author           : Ilia
// Created          : 06-11-2011
//
// Last Modified By : Ilia
// Last Modified On : 01-04-2010
// Description      : 
//
// Copyright        : (c) Microsoft. All rights reserved.
//***********************************************************************
using System;
using System.Reactive.Linq;
using IGolovkine.AoA.Tcp;

namespace IGolovkine.AoA.Tests
{
    public class TunnelAcidTest
    {
        private readonly ChannelTestBed<Message> _client;
        private readonly ChannelTestBed<Message> _server;

        public TunnelAcidTest(TimeSpan timeout, IChannel<Message> clientSideTransport, IChannel<Message> serverSideTransport)
        {
            _client = ChannelTestBed<Message>.Wrap(timeout, clientSideTransport);
            _server = ChannelTestBed<Message>.Wrap(timeout, serverSideTransport);
        }


        public void Run()
        {
            for (int i = 0; i < 10; i++)
            {
                    // client.Input => server.Output
                    TcpConnectionInitiated tunnelConnection = new TcpConnectionInitiated(CorrelationId.Next(), Guid.NewGuid().ToString(), 123);
                    _client.Input.OnNext(tunnelConnection);
                    MessageAssert.AreEqual(tunnelConnection, _server.PopLastOutput().Value);

                    AcceptTcpConnections tunnelPort = new AcceptTcpConnections(123, Guid.NewGuid().ToString(), 245);
                    _client.Input.OnNext(tunnelPort);

                    MessageAssert.AreEqual(tunnelPort, _server.PopLastOutput().Value);

                    TestPacket packet = new TestPacket(100);
                    TcpConnectionMessage notificationSent = new TcpConnectionData(CorrelationId.Next(), packet.GetData());
                    _client.Input.OnNext(notificationSent);

                    //Size could change, message might get fragmented or aggregated
                    MessageAssert.AreEqual(notificationSent, _server.PopLastOutput().Value);

                    //server.Input => client.Output
                    _server.Input.OnNext(notificationSent);
                    MessageAssert.AreEqual(notificationSent, _client.PopLastOutput().Value);

                    _server.Input.OnNext(tunnelPort);
                    MessageAssert.AreEqual(tunnelPort, _client.PopLastOutput().Value);

                    _server.Input.OnNext(tunnelConnection);
                    MessageAssert.AreEqual(tunnelConnection, _client.PopLastOutput().Value);

            } 
        }
       
    }
}
